/**
 * 编辑数据源页面
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  message,
  Row,
  Col,
  Upload,
  Alert,
  Spin,
} from 'antd';
import {
  DatabaseOutlined,
  FileTextOutlined,
  FileExcelOutlined,
  UploadOutlined,
  ApiOutlined,
} from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import type { UploadFile } from 'antd/es/upload/interface';
import {
  getDataSource,
  updateDataSource,
  testConnection,
  uploadFile,
  getExcelSheets,
  type DataSourceUpdate,
  type DataSourceItem,
} from '@/services/dataSource';

const { Option } = Select;
const { TextArea } = Input;

const EditDataSource: React.FC = () => {
  const params = useParams();
  const dataSourceId = parseInt(params.id as string);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [pageLoading, setPageLoading] = useState(true);
  const [testLoading, setTestLoading] = useState(false);
  const [dataSourceInfo, setDataSourceInfo] = useState<DataSourceItem | null>(null);
  const [uploadedFile, setUploadedFile] = useState<string>('');
  const [excelSheets, setExcelSheets] = useState<string[]>([]);

  // 获取数据源信息
  const fetchDataSource = async () => {
    try {
      const data = await getDataSource(dataSourceId);
      setDataSourceInfo(data);
      
      // 设置表单初始值
      form.setFieldsValue({
        name: data.name,
        type: data.type,
        config: data.config,
      });

      // 如果是文件类型，设置文件路径
      if ((data.type === 'csv' || data.type === 'excel') && data.config.file_path) {
        setUploadedFile(data.config.file_path);
        
        // 如果是Excel文件，获取工作表列表
        if (data.type === 'excel') {
          try {
            const sheets = await getExcelSheets(data.config.file_path);
            setExcelSheets(sheets.sheets);
          } catch (error) {
            console.warn('获取Excel工作表失败:', error);
          }
        }
      }
    } catch (error: any) {
      message.error(error.message || '获取数据源信息失败');
      history.push('/datasources');
    } finally {
      setPageLoading(false);
    }
  };

  useEffect(() => {
    if (dataSourceId) {
      fetchDataSource();
    }
  }, [dataSourceId]);

  // 处理文件上传
  const handleFileUpload = async (file: File) => {
    try {
      const result = await uploadFile(file);
      setUploadedFile(result.file_path);
      form.setFieldsValue({
        config: {
          ...form.getFieldValue('config'),
          file_path: result.file_path,
        },
      });

      // 如果是Excel文件，获取工作表列表
      if (dataSourceInfo?.type === 'excel') {
        const sheets = await getExcelSheets(result.file_path);
        setExcelSheets(sheets.sheets);
      }

      message.success('文件上传成功');
      return false;
    } catch (error: any) {
      message.error(error.message || '文件上传失败');
      return false;
    }
  };

  // 测试连接
  const handleTestConnection = async () => {
    try {
      const values = await form.validateFields(['config']);
      setTestLoading(true);

      const result = await testConnection({
        type: dataSourceInfo!.type,
        config: values.config,
      });

      if (result.success) {
        message.success(result.message);
      } else {
        message.error(result.message);
      }
    } catch (error: any) {
      if (error.errorFields) {
        message.error('请先完善配置信息');
      } else {
        message.error(error.message || '连接测试失败');
      }
    } finally {
      setTestLoading(false);
    }
  };

  // 提交表单
  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const data: DataSourceUpdate = {
        name: values.name,
        config: values.config,
      };

      await updateDataSource(dataSourceId, data);
      message.success('数据源更新成功');
      history.push('/datasources');
    } catch (error: any) {
      message.error(error.message || '更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 渲染配置表单
  const renderConfigForm = () => {
    if (!dataSourceInfo) return null;

    switch (dataSourceInfo.type) {
      case 'mysql':
        return (
          <>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name={['config', 'host']}
                  label="主机地址"
                  rules={[{ required: true, message: '请输入主机地址' }]}
                >
                  <Input placeholder="例如: localhost" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['config', 'port']}
                  label="端口"
                  rules={[{ required: true, message: '请输入端口' }]}
                >
                  <Input type="number" placeholder="3306" />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name={['config', 'database']}
                  label="数据库名"
                  rules={[{ required: true, message: '请输入数据库名' }]}
                >
                  <Input placeholder="数据库名称" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['config', 'charset']}
                  label="字符集"
                >
                  <Select>
                    <Option value="utf8mb4">utf8mb4</Option>
                    <Option value="utf8">utf8</Option>
                    <Option value="latin1">latin1</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name={['config', 'username']}
                  label="用户名"
                  rules={[{ required: true, message: '请输入用户名' }]}
                >
                  <Input placeholder="数据库用户名" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['config', 'password']}
                  label="密码"
                  rules={[{ required: true, message: '请输入密码' }]}
                >
                  <Input.Password placeholder="数据库密码" />
                </Form.Item>
              </Col>
            </Row>
          </>
        );

      case 'csv':
        return (
          <>
            <Form.Item
              name={['config', 'file_path']}
              label="CSV文件"
              rules={[{ required: true, message: '请上传CSV文件' }]}
            >
              <Upload
                beforeUpload={handleFileUpload}
                accept=".csv"
                maxCount={1}
                showUploadList={false}
              >
                <Button icon={<UploadOutlined />}>
                  {uploadedFile ? '重新上传' : '上传CSV文件'}
                </Button>
              </Upload>
            </Form.Item>
            {uploadedFile && (
              <Alert
                message={`当前文件: ${uploadedFile.split('/').pop()}`}
                type="info"
                style={{ marginBottom: 16 }}
              />
            )}
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name={['config', 'encoding']}
                  label="编码格式"
                >
                  <Select>
                    <Option value="utf-8">UTF-8</Option>
                    <Option value="gbk">GBK</Option>
                    <Option value="gb2312">GB2312</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['config', 'delimiter']}
                  label="分隔符"
                >
                  <Select>
                    <Option value=",">逗号 (,)</Option>
                    <Option value=";">分号 (;)</Option>
                    <Option value="\t">制表符 (\t)</Option>
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name={['config', 'has_header']}
              label="包含表头"
              valuePropName="checked"
            >
              <Select>
                <Option value={true}>是</Option>
                <Option value={false}>否</Option>
              </Select>
            </Form.Item>
          </>
        );

      case 'excel':
        return (
          <>
            <Form.Item
              name={['config', 'file_path']}
              label="Excel文件"
              rules={[{ required: true, message: '请上传Excel文件' }]}
            >
              <Upload
                beforeUpload={handleFileUpload}
                accept=".xlsx,.xls"
                maxCount={1}
                showUploadList={false}
              >
                <Button icon={<UploadOutlined />}>
                  {uploadedFile ? '重新上传' : '上传Excel文件'}
                </Button>
              </Upload>
            </Form.Item>
            {uploadedFile && (
              <Alert
                message={`当前文件: ${uploadedFile.split('/').pop()}`}
                type="info"
                style={{ marginBottom: 16 }}
              />
            )}
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name={['config', 'sheet_name']}
                  label="工作表"
                >
                  <Select placeholder="选择工作表（默认第一个）">
                    {excelSheets.map((sheet) => (
                      <Option key={sheet} value={sheet}>
                        {sheet}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name={['config', 'start_row']}
                  label="起始行"
                >
                  <Input type="number" placeholder="0" />
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name={['config', 'has_header']}
              label="包含表头"
              valuePropName="checked"
            >
              <Select>
                <Option value={true}>是</Option>
                <Option value={false}>否</Option>
              </Select>
            </Form.Item>
          </>
        );

      default:
        return null;
    }
  };

  if (pageLoading) {
    return (
      <PageContainer>
        <div style={{ textAlign: 'center', padding: 50 }}>
          <Spin size="large" />
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer
      header={{
        title: '编辑数据源',
        breadcrumb: {},
      }}
    >
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          style={{ maxWidth: 800 }}
        >
          <Form.Item
            name="name"
            label="数据源名称"
            rules={[
              { required: true, message: '请输入数据源名称' },
              { min: 2, message: '名称至少2个字符' },
            ]}
          >
            <Input placeholder="请输入数据源名称" />
          </Form.Item>

          <Form.Item label="数据源类型">
            <Input
              value={dataSourceInfo?.type?.toUpperCase()}
              disabled
              addonBefore={
                dataSourceInfo?.type === 'mysql' ? (
                  <DatabaseOutlined style={{ color: '#1890ff' }} />
                ) : dataSourceInfo?.type === 'csv' ? (
                  <FileTextOutlined style={{ color: '#52c41a' }} />
                ) : (
                  <FileExcelOutlined style={{ color: '#fa8c16' }} />
                )
              }
            />
          </Form.Item>

          <Card title="配置信息" size="small" style={{ marginBottom: 24 }}>
            {renderConfigForm()}
            <Form.Item>
              <Button
                icon={<ApiOutlined />}
                onClick={handleTestConnection}
                loading={testLoading}
              >
                测试连接
              </Button>
            </Form.Item>
          </Card>



          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                更新数据源
              </Button>
              <Button onClick={() => history.push('/datasources')}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default EditDataSource;
